package com.lucy.rabc.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Opt;
import com.lucy.common.constant.HttpStatus;
import com.lucy.common.domain.ResponseDTO;
import com.lucy.rabc.entity.SysMenu;
import com.lucy.rabc.entity.SysPost;
import com.lucy.rabc.entity.SysRole;
import com.lucy.rabc.entity.SysRoleMenu;
import com.lucy.rabc.params.RoleCreateParams;
import com.lucy.rabc.params.RoleQueryParams;
import com.lucy.rabc.params.RoleUpdateParams;
import com.lucy.rabc.service.SysMenuService;
import com.lucy.rabc.service.SysRoleMenuService;
import com.lucy.rabc.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author kindear
 */
@Slf4j
@RestController
@RequestMapping("system")
@Api(tags = "角色管理")
public class RoleController {
    @Autowired
    SysRoleService roleService;

    @Autowired
    SysMenuService menuService;

    @Autowired
    SysRoleMenuService roleMenuService;

    @PostMapping("roles")
    @ApiOperation(value = "角色新建",notes = "")
    public ResponseDTO<Object> RoleCreate(@RequestBody @Validated RoleCreateParams params){
        SysRole role = new SysRole();
        BeanUtil.copyProperties(params,role, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));

        List<Long> menuIds = params.getMenuIds();

        List<SysMenu> menus = menuService.getMenus(menuIds);

        List<String> perms = menus.stream().map(SysMenu::getPerms).collect(Collectors.toList());

        role.setPermission(perms);

        SysRole res = roleService.saveOne(role);
        Long roleId = res.getId();
        roleMenuService.batchSetRoleMenus(roleId,menuIds);
        return ResponseDTO.succData(
                res
        );
    }

    @DeleteMapping("roles/{roleId}")
    @ApiOperation(value = "角色删除",notes = "")
    public ResponseDTO<Object> RoleDelete(@PathVariable("roleId") Long roleId){
        roleService.deleteOne(roleId);
        roleMenuService.deleteByRoleId(roleId);
        return ResponseDTO.succMsg("删除成功");
    }

    @PutMapping("roles")
    @ApiOperation(value = "角色修改",notes = "")
    public ResponseDTO<Object> RoleUpdate(@RequestBody @Validated RoleUpdateParams params){
        Long roleId = params.getId();
        Optional<SysRole> roleOp = roleService.getOne(roleId);
        if (!roleOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND);
        }
        SysRole role = roleOp.get();
        BeanUtil.copyProperties(params,role,CopyOptions.create().setIgnoreError(true).setIgnoreNullValue(true));
        List<Long> menuIds = params.getMenuIds();

        List<SysMenu> menus = menuService.getMenus(menuIds);

        List<String> perms = menus.stream().map(SysMenu::getPerms).collect(Collectors.toList());

        role.setPermission(perms);

        roleMenuService.batchSetRoleMenus(roleId,menuIds);
        return ResponseDTO.succData(
                roleService.updateOne(role)
        );
    }

    @GetMapping("roles/{roleId}")
    @ApiOperation(value = "角色查询",notes = "")
    public ResponseDTO<Object> RoleQuery(@PathVariable("roleId") Long roleId){
        Optional<SysRole> roleOp = roleService.getOne(roleId);
        if (!roleOp.isPresent()){
            return ResponseDTO.wrap(HttpStatus.NOT_FOUND);
        }
        SysRole role = roleOp.get();
        List<Long> menuIds = roleMenuService.getRoleMenuIds(roleId);
        Map<String, Object> map = BeanUtil.beanToMap(role);
        map.put("menuIds",menuIds);
        return ResponseDTO.succData(map);
    }

    @GetMapping("roles")
    @ApiOperation(value = "角色列表",notes = "")
    public ResponseDTO<Object> RoleListQuery(RoleQueryParams params){
        Sort sort;
        if(params.getOrder().equalsIgnoreCase("DESC")){
            sort = Sort.by(Sort.Direction.DESC, params.getSortBy());
        }else {
            sort = Sort.by(Sort.Direction.ASC, params.getSortBy());
        }

        // tips : 页码对应 - 1
        Pageable pageable = PageRequest.of(params.getPageNum() - 1 , params.getPageSize(), sort);
        /*
        构建 Example
         */
        SysRole role = new SysRole();
        BeanUtil.copyProperties(params,role,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Example<SysRole> example = Example.of(role);
        return ResponseDTO.succData(roleService.getAll(pageable,example));
    }
}
